import React from 'react';
import {Form, Input, Modal, message} from 'antd';
import {RoleApi} from '@/api/index'

export default class Add extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            modalVisible: false,
        };
        this.formRef = React.createRef();
    }

    static getDerivedStateFromProps(props, state) {
        return {modalVisible: props.modalVisible};
    }

    handleOk = async e => {
        let data = await this.formRef.current.validateFields();
        let ret = await RoleApi.addRole(data);
        if (ret && ret.code === 200) {
            message.success('增加角色成功！');
            this.onClose()
            this.setState({
                modalVisible: false,
            });
        } else {
            message.error(ret.message);
        }
    };

    handleCancel = async e => {
        this.onClose()
        this.setState({
            modalVisible: false,
        });
    };

    onClose(){
        this.props.onClose && this.props.onClose()
    }

    render() {

        return (
            <Modal
                title={"增加角色"}
                open={this.state.modalVisible}
                onOk={this.handleOk}
                onCancel={this.handleCancel}
                destroyOnClose={true}
            >
                <Form ref={this.formRef} wrapperCol={{span: 14}} labelCol={{span: 6}}>
                    <Form.Item name="name" label="名称" rules={[{required: true, message: "请输入名称"}]}>
                        <Input maxLength={20} allowClear autoComplete={"off"}/>
                    </Form.Item>
                    <Form.Item name="code" label="编码" rules={[{required: true, message: "请输入编码"}, {pattern: /^[A-Z]+$/, message: "请输入大写字母"}]}>
                        <Input maxLength={20} allowClear autoComplete={"off"}/>
                    </Form.Item>
                </Form>
            </Modal>
        );
    }
}
